#include "wire.h"
#include "STC89C5xRC.H"

sbit WIRE_IO = P2 ^ 4;

void wire_init(void)
{
    WIRE_IO = 1;
    WIRE_IO = 0;
    delay_us(500); /* delay 530us */
    WIRE_IO = 1;
    delay_us(90); /* delay 100us */

    // if (WIRE_IO == 0)
    //     flag = 1; /* option ok */
    // else
    //     flag = 0; /* option fail */

    delay_us(100); /* delay 130us */
    WIRE_IO = 1;
}

void wire_write_byte(uint8_t dat)
{
    uint8_t i;
    for (i = 0; i < 8; i++)
    {
        WIRE_IO = 0;
        WIRE_IO = dat & 0x01;
        delay_us(22); /* 45 us */
        WIRE_IO = 1;
        dat >>= 1;
    }
}

uint8_t wire_read_byte(void)
{
    uint8_t i;
    uint8_t u = 0;
    for (i = 0; i < 8; i++)
    {
        WIRE_IO = 0;
        u >>= 1;
        WIRE_IO = 1;
        if (WIRE_IO == 1)
            u |= 0x80;
        delay_us(15); /* 15 us */
    }
    return (u);
}
